package com.za.plugin.util;



import com.za.plugin.pojo.Content;
import com.za.plugin.pojo.PredixStrAndCount;
import org.apache.ibatis.executor.statement.PreparedStatementHandler;
import org.apache.ibatis.mapping.MappedStatement;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class StrUtil {

    private StrUtil() {
    }
    // id 包含当前 mapper接口名称和方法，可用于调试
    private String getCurrentExecuteMethodName(PreparedStatementHandler delegate) {
        try {
            Field mappedStatementField = delegate.getClass().getSuperclass().getDeclaredField("mappedStatement");
            mappedStatementField.setAccessible(true);
            MappedStatement mappedStatement = (MappedStatement) mappedStatementField.get(delegate);
            return mappedStatement.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    // 获取期望的 () 内的内容
    public static Content getExpectContent(String sql, int start) {
        int cnt = 0, j = start;
        while (j < sql.length()) {
            if (sql.charAt(j) == '(') {
                cnt++;
            }
            if (sql.charAt(j) == ')') {
                cnt--;
            }
            j++;
            if (cnt == 0) {
                return new Content(sql.substring(start + 1, j - 1), j);
            }
        }
        return null;
    }

    public static List<String> getSegment(String sql, int left, int right) {
        List<String> list = new ArrayList<>();
        int leftFlag = 0, j = left, start = left;
        while (j < right) {
            char ch = sql.charAt(j);
            if (ch == ',' && leftFlag == 0) {
                list.add(sql.substring(start, j).trim());
                start = j + 1;
            }
            if (ch == '(') {
                leftFlag++;
            }
            if (ch == ')') {
                leftFlag--;
            }
            if (j == right - 1) {
                String substr = sql.substring(start, right).trim();
                if (substr.length() > 0) {
                    list.add(substr);
                }
            }
            j++;
        }
        return list;
    }

    public static List<String> getSegment2(String sql, int left, int right) {
        List<String> list = new ArrayList<>();
        int leftFlag = 0, j = left, start = left;
        while (j < right) {
            char ch = sql.charAt(j);
            if (ch == ',' && leftFlag == 0) {
                list.add(sql.substring(start, j).trim());
                start = j + 1;
            }
            if (ch == '<') {
                leftFlag++;
            }
            if (ch == '>') {
                leftFlag--;
            }
            if (j == right - 1) {
                String substr = sql.substring(start, right).trim();
                if (substr.length() > 0) {
                    list.add(substr);
                }
            }
            j++;
        }
        return list;
    }

    // 设置为 非[a-zA-Z0-9_.] ?
    public static boolean isValidSeparator(char ch) {
        return ch == ' ' || ch == '\"' || ch == '\'' || ch == '(' || ch == ')'
                || ch == ',' || ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '>' || ch == '<' || ch == '=';
    }

    public static String swapWord(String substring, String key, String value) {
        int idx = substring.indexOf(key), len = key.length();
        while (idx >= 0) {
            StringBuilder sb = new StringBuilder();
            if ((idx == 0 || isValidSeparator(substring.charAt(idx - 1))) &&
                    ((idx + len == substring.length()) || isValidSeparator(substring.charAt(idx + len)))) {
                sb.append(substring, 0, idx).append(value);
                if (!(idx + len == substring.length())) {
                    sb.append(substring.substring(idx + len));
                }
                substring = sb.toString();
            }
            idx = substring.indexOf(key, idx + 1);
        }
        return substring;
    }

    public static boolean checkRightIdx(String sql, int left, int right) {
        int leftNum = 0, j = left;
        while (j < right) {
            if (sql.charAt(j) == '(') {
                leftNum++;
            } else if (sql.charAt(j) == ')') {
                leftNum--;
            }
            j++;
        }
        return leftNum == 0;
    }

    // 转为小驼峰写法
    public static String toJavaProperty(String word) {
        StringBuilder sb = new StringBuilder();
        int len = word.length();
        for (int i = 0; i < len; i++) {
            if (i > 0 && word.charAt(i) == '_') {
                if (word.charAt(i+1) <= 'z' && word.charAt(i+1) >= 'a') {
                    sb.append((char) (word.charAt(i+1) - 'a' + 'A'));
                    i++;
                }
            } else {
                sb.append(word.charAt(i));
            }
        }
        return sb.toString().trim();
    }

    // 转为 '_' 连接的名称
    public static String toSqlProperty(String name) {
        StringBuilder sb = new StringBuilder();
        char[] chars = name.toCharArray();
        for (char ch : chars) {
            if (ch <= 'z' && ch >= 'a') {
                sb.append(ch);
            } else if (ch >= 'A' && ch <= 'Z') {
                sb.append("_").append((char) (ch - 'A' + 'a'));
            } else {
                sb.append(ch);
            }
        }
        return  sb.toString();
    }

    public static PredixStrAndCount getPredixStrAndCount(List<String> keys) {
        int max = 0;
        Pattern pattern = Pattern.compile("\\d+");
        String iteratorPrefix = "";
        for (String key : keys) {
            String[] split = key.split("\\.");
            Matcher matcher = pattern.matcher(split[0]);
            while (matcher.find()) {
                int number = Integer.parseInt(matcher.group().trim());
                max = Math.max(max, number);
                if ("".equals(iteratorPrefix)) {
                    int index = split[0].indexOf("" + number);
                    iteratorPrefix = split[0].substring(0, index).trim();
                }
            }
        }

        return new PredixStrAndCount(iteratorPrefix, max + 1);
    }



    public static List<String> getKeyName(List<String> keys) {
        if (keys == null || keys.size() == 0) {
            return Collections.emptyList();
        }
        return keys.stream().map(it -> it.contains(".") ? it.split("\\.")[1] : it)
                .distinct().collect(Collectors.toList());
    }

    public static boolean isLetter(char ch) {

        return ch == '_' || Character.isLetter(ch);
    }

    public static int getCount(String sql, String s) {
        int idx = sql.indexOf(s);
        if (idx == -1) {
            return 0;
        }
        int cnt = 0;
        while (idx != -1) {
            cnt++;
            idx = sql.indexOf(s, idx + s.length());
        }
        return cnt;
    }

    // 如果不在数据库设置屏蔽关键字，就在这里写代码。 comment => "COMMENT"
    public static String transKeyWord(String word) {
        return word;
//        if (!"comment".equalsIgnoreCase(word)) {
//            return word;
//        }
//        return "\"" + word.toUpperCase() + "\"";
    }

}
